package com.example.pluto.common.utils;

import cn.hutool.core.codec.Base64;
import cn.hutool.crypto.SecureUtil;
import com.alibaba.fastjson.JSON;
import com.example.pluto.user.entity.PlutoUser;

import java.util.Date;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.UUID;

/**
 *@Author Mr.Yang
 *@Date 2025/1/10
 *@Description TODO
 */
public class SignUtils {

    public static void main(String[] args) {
        PlutoUser plutoUser = new PlutoUser();
        plutoUser.setId(1L);
        plutoUser.setCreateTime(new Date());
        plutoUser.setAddress("重庆市");
        Map<String, String> map = buildSignMap(plutoUser);
        addSignature(map);
        mapToSignatureString(map);
        System.out.println(map.get("sign"));
        String stringSignTemp = destroySignMap(map);
        System.out.println(SecureUtil.md5(stringSignTemp).toUpperCase());
        String decodeStr = Base64.decodeStr(map.get("data"));
        System.out.println(decodeStr);
    }

    private final static String APP_ID = "appid";
    private final static String KEY = "key";
    private final static String VERSION = "1.0.1";

    private static String destroySignMap(Map<String, String> map) {
        return mapToSignatureString(map);
    }

    private static Map<String, String> buildSignMap(Object requestBody) {
        String encodedData = Base64.encode(JSON.toJSONString(requestBody));
        String noise = UUID.randomUUID().toString().replaceAll("-", "").toUpperCase();
        Map<String, String> signMap = new LinkedHashMap<>();
        signMap.put("appid", APP_ID);
        signMap.put("data", encodedData);
        signMap.put("noise", noise);
        signMap.put("key", KEY);
        signMap.put("version", VERSION);
        return signMap;
    }

    private static void addSignature(Map<String, String> signMap) {
        String stringSignTemp = mapToSignatureString(signMap);
        signMap.put("sign", SecureUtil.md5(stringSignTemp).toUpperCase());
    }

    private static String mapToSignatureString(Map<String, String> map) {
        // 实现签名字符串拼接逻辑
        StringBuilder sb = new StringBuilder();
        for (Map.Entry<String, String> entry : map.entrySet()) {
            if (!"sign".equals(entry.getKey())) {
                sb.append(entry.getKey()).append("=").append(entry.getValue()).append("&");
            }
        }
        return sb.toString().replaceAll(".$", "");
    }

}
